import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../pages/settings/locale/locale_controller.dart';
import '../pages/settings/theme/theme_controller.dart';
import 'log/log_printer.dart';

class AppInitializer {
  AppInitializer._();

  static final ThemeController themeController = ThemeController();
  static final LocaleController localeController = LocaleController();
  static late SharedPreferences prefs;
  static late CacheManager cacheManager;
  static late Logger logger;

  /// 初始化入口
  static Future<void> initialize() async {
    WidgetsFlutterBinding.ensureInitialized();

    await _initLogger();
    await _initStorage();
    await _initCacheManager();
    await _initTheme();
    await _initLocale();
    await _initScreenUtil();
    await _initLocalization();
    await _initJpush();
  }

  /// 初始化日志系统
  static Future<void> _initLogger() async {
    logger = Logger(
      printer: SimpleLogPrinter("WaterQualityApp"),
      level: Level.info,
    );
    logger.i("Logger initialized");
  }

  /// 初始化 SharedPreferences
  static Future<void> _initStorage() async {
    prefs = await SharedPreferences.getInstance();
    logger.i("SharedPreferences initialized");
  }

  /// 初始化缓存管理器
  static Future<void> _initCacheManager() async {
    cacheManager = CacheManager(
      Config(
        'szsw_water_quality_cache',
        stalePeriod: const Duration(days: 30),
        maxNrOfCacheObjects: 200,
      ),
    );
    logger.i("CacheManager initialized");
  }

  /// 初始化主题控制器
  static Future<void> _initTheme() async {
    await themeController.loadTheme();
    logger.i("Theme loaded");
  }

  /// 初始化语言控制器
  static Future<void> _initLocale() async {
    await localeController.loadLocale();
    logger.i("Locale loaded");
  }

  /// 初始化屏幕适配
  static Future<void> _initScreenUtil() async {
    await ScreenUtil.ensureScreenSize();
    logger.i("ScreenUtil initialized");
  }

  /// 初始化本地化（这里只是占位，具体逻辑可扩展）
  static Future<void> _initLocalization() async {
    // 如果你未来支持远程语言资源或动态切换，可以在这里扩展
    logger.i("Localization initialized");
  }

  static Future<void> _initJpush() async {
    logger.i("JPush initialized");
  }
}
